package reverseWords;

public class Solution {
    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int i = 0,j = 0;
        while (i<s.length()&&j<s.length()) {
            if (!checkFirst(i,chars)) {
                i++;
                j = i;
            } else if (!checkLast(j,chars)) {
                j++;
            } else {
                reverse(chars,i,j);
                i = j+1;
            }
        }
        return new String(chars);
    }
    private boolean checkFirst(int i,char[] chars) {
        if(i==0)return chars[i]!=' ';
        return chars[i-1]==' '&&chars[i]!=' ';
    }
    private boolean checkLast(int i,char[] chars) {
        if(i==chars.length-1) return chars[i]!=' ';
        return chars[i]!=' '&&chars[i+1]==' ';
    }
    private void reverse(char[] chars,int start,int end) {
        int i = start,j = end;
        while (i<j) {
            char t = chars[i];
            chars[i++] = chars[j];
            chars[j--] = t;
        }
    }
}
